import sys
from bookstore.Book import Book
from bookstore.BookNotFoundException import BookNotFoundException

class CommandBookstore(object):
    def __init__(self, bookstore):
        self.bookstore = bookstore

    def _printBook(self, book):
        print '%s:%s-%s' % (book.ISBN, book.author, book.title)
        

    def getCommand( self ):
        self.printHelp()

        while True:
            commandLine = raw_input('> ')
            args = commandLine.split(' ')
            if args == []:
                continue

            command = args[0]
            try:
                func = getattr(self, command)
            except:
                print "unrecognized command 'help' for details"
                continue

            try:
                if len(args) > 1:
                    func( ' '.join(args[1:]) )
                else:
                    func()                    
            except SystemExit:
                raise
            except:
                import traceback
                traceback.print_exc()

            
    def printHelp(self):
        print 'quit - finish'
        print 'help - this help'
        print 'list - list current books'
        print 'save <filename> - save current booklist'
        print 'load <filename> - load a booklist'
        print 'delete <isbn> - delete a book'
        print 'add - add a new book'
        print 'find <author> - list books by author'


    def quit(self):
        sys.exit()

    def help(self):
        self.printHelp()

    def list(self):
        books = self.bookstore.getAllBooks()
        if len(books) == 0:
            print 'bookstore empty'
            return

        for book in books:
            self._printBook(book)

    def save(self, filename):
        self.bookstore.saveBooks(filename)
    
    def load(self, filename):
        self.bookstore.loadBooks(filename)

    def find(self, author):
        books = self.bookstore.findBooksByAuthor( author )
        if len(books) == 0:
            print 'no books by selected author'
            return

        for book in books:
            self._printBook(book)

    def delete(self, isbn):
        try:
            book = self.bookstore.getBookByIsbn(isbn)
        except BookNotFoundException:
            print 'Book not found'
            return

        self.bookstore.removeBook( book.ISBN )
        print 'book deleted'

    def add(self):
        isbn = raw_input('isbn: ')
        title = raw_input('title: ')
        author = raw_input('author: ')
        description = raw_input('description: ')
        book = Book( isbn, title, description, author )
        if self.bookstore.addBook(book):
            print 'book added'
        else:
            print 'book not accepted'
